package com.qdsgjsfk.vision.ui.dialog;

import android.annotation.SuppressLint;
import android.app.Dialog;
import android.graphics.Rect;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.qdsgjsfk.vision.adapter.PointAdapter;
import com.qdsgjsfk.vision.base.BaseApplication;
import com.qdsgjsfk.vision.base.BaseDialogFragment;
import com.qdsgjsfk.vision.eventbus.SocketInput;
import com.qdsgjsfk.vision.model.Msg;
import com.qdsgjsfk.vision.model.Point;
import com.qdsgjsfk.vision.util.Constant;

import com.qdsgjsfk.vision.R;

import org.greenrobot.eventbus.EventBus;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

import com.qdsgjsfk.vision.ui.widget.CustomPopWindow;

import util.PreferencesHelper;

/**
 * Created by HP on 2018/10/5.
 */

public class VisionDialog extends BaseDialogFragment {

    public static VisionDialog newInstance(String title, String vision) {
        Bundle args = new Bundle();
        args.putString("vision", vision);
        args.putString("title", title);
        VisionDialog fragment = new VisionDialog();
        fragment.setArguments(args);
        return fragment;
    }

    private Dialog mDialog;
    private OnItemClickListener mListener;
    private TextView btn_clear, btn_cancel, btn_confirm, tv_title, tv_distance;
    private RecyclerView recyclerView_vision, recyclerView_point;
    private MyAdapter myAdapter_vision;
    private PointAdapter pointAdapter;
    private List<VisionInfo> list_vision = new ArrayList<>();
    private List<Point> pointList = new ArrayList<>();
    private String current;
    int currentPosition;
    private long firstTime = 0;
    private String currentVision;
    private CustomPopWindow mPopWindow;

    @Override

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_vision, container);
        currentVision = getArguments().getString("vision");
//        btn_confirm = view.findViewById(R.id.btn_confirm);
        myAdapter_vision = new MyAdapter(list_vision);
        recyclerView_point = view.findViewById(R.id.point_recyclerView);
        pointAdapter = new PointAdapter(getActivity(), pointList, PreferencesHelper.getInstance().getInt(getActivity(), Constant.CHART_TYPE, 1), directionOrType -> {
            if (currentPosition < 0) {
                EventBus.getDefault().postSticky(new SocketInput(new Msg.Builder().code(Constant.CODE_TEACHER_OPERATE).size(0).value(directionOrType + "").build().toString()));
            } else {
                EventBus.getDefault().postSticky(new SocketInput(new Msg.Builder().code(Constant.CODE_TEACHER_OPERATE).size(currentPosition).value(directionOrType + "").build().toString()));
            }
        });
        recyclerView_point.setAdapter(pointAdapter);
        recyclerView_point.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        initList();
        btn_clear = view.findViewById(R.id.btn_clear);
        btn_clear.setOnClickListener(v -> {
            dismiss();
            if (mListener != null) {
                mListener.onConfirm("");
            }
        });
        btn_cancel = view.findViewById(R.id.btn_cancel);
        btn_cancel.setOnClickListener(v -> {
            EventBus.getDefault().postSticky(new SocketInput(new Msg.Builder().code(Constant.CODE_QUIT).value("").build().toString()));
            dismiss();
        });
        btn_confirm = view.findViewById(R.id.btn_confirm);
        btn_confirm.setOnClickListener(v -> {
            if (mListener != null) {

                mListener.onConfirm(current);
            }
            dismiss();
        });
        tv_title = view.findViewById(R.id.tv_title);
        tv_title.setText(getArguments().getString("title"));
        tv_distance = view.findViewById(R.id.tv_distance);
        if (PreferencesHelper.getInstance().getInt(getActivity(), Constant.CHART_TYPE, 1) == Constant.CHART_TEACHER_E_2_5)
            tv_distance.setText("测量距离2.5米");
        else
            tv_distance.setText("测量距离5米");


        recyclerView_vision = view.findViewById(R.id.recyclerView_vision);
        recyclerView_vision.setLayoutManager(new GridLayoutManager(getActivity(), 4));
        recyclerView_vision.setAdapter(myAdapter_vision);
        recyclerView_vision.addItemDecoration(new RecyclerView.ItemDecoration() {
            @Override
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                super.getItemOffsets(outRect, view, parent, state);
                outRect.bottom = 50;
                outRect.left = 20;
                outRect.right = 20;
            }
        });
        DecimalFormat decimalFormat = new DecimalFormat("0.0");

        if (PreferencesHelper.getInstance().getInt(getActivity(), Constant.CHART_TYPE, 1) == Constant.CHART_TEACHER_E_2_5) {
            for (int i = 0; i < 21; i++) {
                list_vision.add(new VisionInfo(decimalFormat.format(Float.parseFloat((30 + i) + "") / 10f), false));
            }
        } else {
            for (int i = 0; i < 24; i++) {
                list_vision.add(new VisionInfo(decimalFormat.format(Float.parseFloat((30 + i) + "") / 10f), false));
            }
        }

        getDialog().setCanceledOnTouchOutside(false);
        new Handler(Looper.getMainLooper()).postDelayed(() -> {
            if (TextUtils.isEmpty(currentVision)) {
                if (PreferencesHelper.getInstance().getInt(getActivity(), Constant.CHART_TYPE, 1) == Constant.CHART_TEACHER_E_2_5) {
                    currentPosition = 2;
                    current = list_vision.get(6).vision;
                    for (int i = 0; i < list_vision.size(); i++) {
                        list_vision.get(i).flag = false;
                    }
                    list_vision.get(6).flag = true;
                } else {
                    currentPosition = 2;
                    current = list_vision.get(9).vision;
                    for (int i = 0; i < list_vision.size(); i++) {
                        list_vision.get(i).flag = false;
                    }
                    list_vision.get(9).flag = true;
                }
                myAdapter_vision.notifyDataSetChanged();
                randomE();
            } else {
                //说明之前已经测量过
                try {
                    float f = 0f;
                    if (PreferencesHelper.getInstance().getInt(getActivity(), Constant.CHART_TYPE, 1) == Constant.CHART_TEACHER_E_2_5) {
                        f = Float.parseFloat(currentVision) * 10 - 37;
                        currentPosition = (int) f;
                        current = list_vision.get((int) f + 7).vision;
                        for (int i = 0; i < list_vision.size(); i++) {
                            list_vision.get(i).flag = false;
                        }
                        list_vision.get((int) f + 7).flag = true;
                    } else {
                        f = Float.parseFloat(currentVision) * 10 - 40;
                        currentPosition = (int) f;
                        current = list_vision.get((int) f + 10).vision;
                        for (int i = 0; i < list_vision.size(); i++) {
                            list_vision.get(i).flag = false;
                        }
                        list_vision.get((int) f + 10).flag = true;
                    }

                    myAdapter_vision.notifyDataSetChanged();
                    randomE();
                } catch (Exception e) {

                } finally {

                }
            }
        }, 500);
        return view;
    }


    private boolean onKey() {
//        long secondTime = System.currentTimeMillis();
//        if (secondTime - firstTime < 500) {
//            Toast.makeText(getActivity(), "您操作的太快了", Toast.LENGTH_SHORT).show();
//            return true;
//        } else {
//            firstTime = secondTime;
//            return false;
//        }
        return false;
    }


//    @Override
//    public void onResume() {
//        super.onResume();
//        String msg = "1,0,aaaaaa";
//        EventBus.getDefault().postSticky(new SocketInput(msg,6666));
//    }

    @Override
    @NonNull
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        mDialog = super.onCreateDialog(savedInstanceState);
        mDialog.setCancelable(false);
        Window window = mDialog.getWindow();
        if (window != null) {
            window.setGravity(Gravity.CENTER);
//            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
//            window.setLayout(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);

        }
        return mDialog;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        Objects.requireNonNull(getDialog().getWindow()).requestFeature(Window.FEATURE_NO_TITLE);
        super.onActivityCreated(savedInstanceState);
        getDialog().getWindow().setBackgroundDrawable(new ColorDrawable(0x00000000));
        getDialog().getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT, WindowManager.LayoutParams.WRAP_CONTENT);
    }

    public OnItemClickListener getmListener() {
        return mListener;
    }

    public void setmListener(OnItemClickListener mListener) {
        this.mListener = mListener;
    }


    public interface OnItemClickListener {

        void onConfirm(String vision);
    }

    public boolean isShowing() {
        return mDialog != null && mDialog.isShowing();
    }

    class MyAdapter extends RecyclerView.Adapter<MyAdapter.Holder> {
        List<VisionInfo> list;

        MyAdapter(List<VisionInfo> list) {
            this.list = list;
        }

        @NonNull
        @Override
        public Holder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            return new Holder(getLayoutInflater().inflate(R.layout.item_vision, parent, false));
        }

        @Override
        public void onBindViewHolder(final Holder holder, @SuppressLint("RecyclerView") final int position) {
            holder.tv_name.setText(list.get(position).vision);
            if (list.get(position).flag) {
                holder.tv_name.setTextColor(getResources().getColor(R.color.white));
                holder.tv_name.setBackgroundResource(R.drawable.item_bg_blue_button);
            } else {
                holder.tv_name.setTextColor(getResources().getColor(R.color.commonBlack));
                holder.tv_name.setBackgroundResource(R.drawable.item_bg_grey_button);
            }
            holder.itemView.setOnClickListener(v -> {
                if (onKey()) {
                    return;
                }
//                    currentPosition = position;
                if (PreferencesHelper.getInstance().getInt(getActivity(), Constant.CHART_TYPE, 1) == Constant.CHART_TEACHER_E_2_5) {
                    currentPosition = position - 7;
                } else {
                    currentPosition = position - 10;
                }
                if (currentPosition >= 0) {
                    String msg = "1," + currentPosition + ",aaaaaa";
//                        EventBus.getDefault().postSticky( new SocketInput( msg, 6666 ) );
                } else {
                    String msg = "1,0,aaaaaa";
//                        EventBus.getDefault().postSticky( new SocketInput( msg, 6666 ) );
                }

                current = list.get(position).vision;
                for (int i = 0; i < list.size(); i++) {
                    list.get(i).flag = false;
                }
                list.get(position).flag = true;
                myAdapter_vision.notifyDataSetChanged();
                randomE();
                if (PreferencesHelper.getInstance().getInt(getActivity(), Constant.CHART_TYPE, 1) == Constant.CHART_TEACHER_E_2_5) {
                    if (position < 7) {
                        showPopListView(v, position);
                    }
                } else {
                    if (position < 10) {
                        showPopListView(v, position);
                    }
                }
            });
        }

        @Override
        public int getItemCount() {
            return list.size();
        }

        class Holder extends RecyclerView.ViewHolder {
            TextView tv_name;

            public Holder(View itemView) {
                super(itemView);
                tv_name = itemView.findViewById(R.id.tv_name);
            }
        }
    }

    private int getRotation() {
        double f = Math.random();
        int rotation = (int) (f * 360 / 90) * 90;
        return rotation;
    }

    private void rotationImage(ImageView e, int rotation) {
        e.setPivotX(e.getWidth() / 2);
        e.setPivotY(e.getHeight() / 2);//支点在图片中心
        double f = Math.random();
        e.setRotation(rotation);
    }


    private void randomE() {
        double f = Math.random();
        int e = (int) (f * 4);
        recyclerView_point.getChildAt(e).performClick();
    }

    static class VisionInfo {

        VisionInfo(String vision, boolean flag) {
            this.vision = vision;
            this.flag = flag;
        }

        String vision;
        boolean flag = false;
    }


    private void showPopListView(View view, int position) {
        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.pop_window, null);
        TextView tv = contentView.findViewById(R.id.tv_pop);
        switch (position) {
            case 0:
                tv.setText("请走到0.5米处");
                break;
            case 1:
                tv.setText("请走到0.6米处");
                break;
            case 2:
                tv.setText("请走到0.8米处");
                break;
            case 3:
                tv.setText("请走到1米处");
                break;
            case 4:
                tv.setText("请走到1.2米处");
                break;
            case 5:
                tv.setText("请走到1.5米处");
                break;
            case 6:
                tv.setText("请走到2米处");
                break;
            case 7:
                tv.setText("请走到2.5米处");
                break;
            case 8:
                tv.setText("请走到3米处");
                break;
            case 9:
                tv.setText("请走到4米处");
                break;
        }

        //创建并显示popWindow
        mPopWindow = new CustomPopWindow.PopupWindowBuilder(getActivity())
                .setView(contentView)
                .setTouchable(false)
                .size(250, ViewGroup.LayoutParams.WRAP_CONTENT) // 显示大小
                .create()
                .showAsDropDown(view, (view.getWidth() - 250) / 2, -10, Gravity.CENTER);
    }


    private void initList() {
        if (PreferencesHelper.getInstance().getInt(getActivity(), Constant.CHART_TYPE, 1) == Constant.CHART_TEACHER_E || PreferencesHelper.getInstance().getInt(getActivity(), Constant.CHART_TYPE, 1) == Constant.CHART_TEACHER_E_2_5) {
            Point point1 = new Point();
            point1.directionOrType = 0;
            pointList.add(point1);
            Point point2 = new Point();
            point2.directionOrType = 90;
            pointList.add(point2);
            Point point3 = new Point();
            point3.directionOrType = 180;
            pointList.add(point3);
            Point point4 = new Point();
            point4.directionOrType = 270;
            pointList.add(point4);
        }
        if (PreferencesHelper.getInstance().getInt(getActivity(), Constant.CHART_TYPE, 1) == Constant.CHART_TEACHER_C) {
            Point point1 = new Point();
            point1.directionOrType = 0;
            pointList.add(point1);
            Point point2 = new Point();
            point2.directionOrType = 45;
            pointList.add(point2);
            Point point3 = new Point();
            point3.directionOrType = 90;
            pointList.add(point3);
            Point point4 = new Point();
            point4.directionOrType = 135;
            pointList.add(point4);
            Point point5 = new Point();
            point5.directionOrType = 180;
            pointList.add(point5);
            Point point6 = new Point();
            point6.directionOrType = 225;
            pointList.add(point6);
            Point point7 = new Point();
            point7.directionOrType = 270;
            pointList.add(point7);
            Point point8 = new Point();
            point8.directionOrType = 315;
            pointList.add(point8);
        }
        if (PreferencesHelper.getInstance().getInt(getActivity(), Constant.CHART_TYPE, 1) == Constant.CHART_TEACHER_ANIMAL) {
            Point point1 = new Point();
            point1.directionOrType = 0;
            point1.resource = R.mipmap.apple;
            pointList.add(point1);
            Point point2 = new Point();
            point2.directionOrType = 1;
            point2.resource = R.mipmap.flower;
            pointList.add(point2);
            Point point3 = new Point();
            point3.directionOrType = 2;
            point3.resource = R.mipmap.duck;
            pointList.add(point3);
            Point point4 = new Point();
            point4.directionOrType = 3;
            point4.resource = R.mipmap.umbrella;
            pointList.add(point4);
            Point point5 = new Point();
            point5.directionOrType = 4;
            point5.resource = R.mipmap.cup;
            pointList.add(point5);
            Point point6 = new Point();
            point6.directionOrType = 5;
            point6.resource = R.mipmap.scissors;
            pointList.add(point6);
            Point point7 = new Point();
            point7.directionOrType = 6;
            point7.resource = R.mipmap.fish;
            pointList.add(point7);
        }
        pointAdapter.notifyDataSetChanged();
    }
}
